package com.hzw.saas.web.app.security;

import cn.hutool.core.text.StrFormatter;
import cn.hutool.core.util.StrUtil;
import com.hzw.saas.api.syslog.ISysLogService;
import com.hzw.saas.api.syslog.model.SysLog;
import com.hzw.saas.common.security.constants.SecurityConstants;
import com.hzw.saas.common.security.filter.AbstractLoginAuthenticationFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;

/**
 * 登录过滤器
 * 适配老版本登录，查询用户实际是调用用户中心接口
 * @author zzl
 * @since 12/21/2020
 */
@Primary
@Component
public class SaasLoginFilter extends AbstractLoginAuthenticationFilter {
    @Resource
    private ISysLogService sysLogService;
    @Resource
    private UserDetailsService userDetailsService;

    public SaasLoginFilter() {
        super(SecurityConstants.LOGIN_URI);
    }

    @Override
    @Autowired
    public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
        this.passwordEncoder = passwordEncoder;
    }

    @Override
    @Autowired
    public void setAuthenticationManager(AuthenticationManager authenticationManager) {
        super.setAuthenticationManager(authenticationManager);
    }

    @Override
    @Autowired
    public void setAuthenticationSuccessHandler(AuthenticationSuccessHandler successHandler) {
        super.setAuthenticationSuccessHandler(successHandler);
    }

    @Override
    @Autowired
    public void setAuthenticationFailureHandler(AuthenticationFailureHandler failureHandler) {
        super.setAuthenticationFailureHandler(failureHandler);
    }

    @Override
    protected UserDetails loadUserByUsername(String username) {
        return userDetailsService.loadUserByUsername(username);
    }

    @Override
    protected void saveDbLog(long time, String username, String errorMsg) {
        try {
            SysLog sysLogEntity = new SysLog();
            //注解
            sysLogEntity.setOperation("用户登录");
            sysLogEntity.setUri(SecurityConstants.LOGIN_URI);
            sysLogEntity.setHttpMethod(getRequestMethod());
            //用户名
            sysLogEntity.setUsername(username);
            //请求的方法名
            sysLogEntity.setClassMethod("");
            //请求的参数
            sysLogEntity.setParams(StrFormatter.format("{username: {}, password: *}", username));
            //执行时间
            sysLogEntity.setTime(time);
            //可能的异常
            if (StrUtil.isNotBlank(errorMsg)) {
                sysLogEntity.setException(errorMsg);
            }
            //设置IP地址
            sysLogEntity.setIp(getIp());
            //log time
            sysLogEntity.setCreateDate(new Date());
            //保存系统日志
            // TODO: ZZL@07/19/2021 增加异步执行
            sysLogService.save(sysLogEntity);
        } catch (Exception e) {
            logger.error("sys log error", e);
        }
    }

}
